import argparse
from datetime import datetime
import threading
import time
import sys
from core.subscription import SubscriptionManager
from config import Config
from report_generator import ReportGenerator

class GiteeSentinelCLI:
    def __init__(self, token, scheduler_enabled=True):
        self.sub_manager = SubscriptionManager()
        self.config = Config()
        self.token =self.config.get_gitee_token()  # Gitee Token
        self.report_generator = ReportGenerator(token=self.token,ollama_url=self.config.get_ollama())
        self.scheduler_enabled = scheduler_enabled
        self.running = True

    def scheduler_task(self):
        """后台任务：定时检查更新"""
        while self.running:
            if self.scheduler_enabled:
                print("\n[Scheduler] Checking for updates...")
                for repo in self.sub_manager.list_subscriptions():
                    print(f"[Scheduler] Generating report for: {repo}")
                    self.report_generator.generate_release_report(repo)
            time.sleep(3600)  # 每小时检查一次

    def handle_add_subscription(self, repo_url):
        """处理增加订阅命令"""
        self.sub_manager.add_subscription(repo_url)

    def handle_remove_subscription(self, repo_url):
        """处理移除订阅命令"""
        self.sub_manager.remove_subscription(repo_url)

    def handle_list_subscriptions(self):
        """处理列出订阅命令"""
        print("Current subscriptions:")
        for repo in self.sub_manager.list_subscriptions():
            print(f"- {repo}")

    def handle_update_report(self, repo_url):
        """处理更新报告命令"""
        self.report_generator.generate_release_report(repo_url)

    def handle_exit(self):
        """处理退出命令"""
        print("Exiting Gitee Sentinel...")
        self.running = False

    def handle_daily(self, repo_url):
        """生成每日进展报告"""
        owner, repo = parse_repo_url(repo_url)
        self.report_generator.generate_daily_report(owner, repo)

    def handle_summarize(self, repo_url):
        """生成项目汇总报告"""
        owner, repo = parse_repo_url(repo_url)
        # 假设 Markdown 文件以 "repo_<YYYY-MM-DD>.md" 格式命名
        date = datetime.now().strftime("%Y-%m-%d")
        daily_report_file = f"reports/{repo}_{date}.md"
        self.report_generator.generate_summary_report(daily_report_file)

    def run(self):
        """启动 CLI 工具"""
        # 启动 Scheduler 线程（如果启用）
        if self.scheduler_enabled:
            scheduler_thread = threading.Thread(target=self.scheduler_task, daemon=True)
            scheduler_thread.start()

        print("Welcome to Gitee Sentinel CLI!")
        print("Type 'help' to see available commands.")

        while self.running:
            command = input("\n> ").strip()
            if command:
                self.handle_command(command)

    def handle_command(self, command):
        """处理命令行输入"""
        cmd_parts = command.split()

        if not cmd_parts:
            return

        action = cmd_parts[0].lower()
        if action == "add" and len(cmd_parts) == 2:
            repo_url = cmd_parts[1]
            self.handle_add_subscription(repo_url)
            print(f"Added subscription: {repo_url}")
        elif action == "remove" and len(cmd_parts) == 2:
            repo_url = cmd_parts[1]
            self.handle_remove_subscription(repo_url)
            print(f"Removed subscription: {repo_url}")
        elif action == "list":
            self.handle_list_subscriptions()
        elif action == "update" and len(cmd_parts) == 2:
            repo_url = cmd_parts[1]
            self.handle_update_report(repo_url)
        if action == "daily" and len(cmd_parts) == 2:
            repo_url = cmd_parts[1]
            self.handle_daily(repo_url)
        elif action == "summarize" and len(cmd_parts) == 2:
            repo_url = cmd_parts[1]
            self.handle_summarize(repo_url)
        elif action == "exit":
            self.handle_exit()
        elif action == "help":
            self.print_help()
        else:
            print("Unknown command. Type 'help' to see the list of commands.")

    def print_help(self):
        """打印帮助信息"""
        help_text = """
Gitee Sentinel CLI Tool Usage:

Commands:
  add <repo_url>    - Add a new subscription for a Gitee repository.
  remove <repo_url> - Remove a subscription for a Gitee repository.
  list              - List all current subscriptions.
  update <repo_url> - Generate and update the report for a specific repository.
  exit              - Exit the tool.
  help              - Show this help message.

Examples:
  > add https://gitee.com/fit2cloud-feizhiyun/MaxKB
  > remove https://gitee.com/fit2cloud-feizhiyun/MaxKB
  > list
  > update https://gitee.com/fit2cloud-feizhiyun/MaxKB
  > exit
"""
        print(help_text)

def create_parser():
    """创建 argparse 解析器，并定义命令和子命令"""
    parser = argparse.ArgumentParser(prog="giteesentinel", description="Gitee Sentinel CLI Tool")
    subparsers = parser.add_subparsers(dest="command")

    # 子命令：add
    add_parser = subparsers.add_parser("add", help="Add a new subscription")
    add_parser.add_argument("repo_url", help="URL of the Gitee repository to subscribe to")

    # 子命令：remove
    remove_parser = subparsers.add_parser("remove", help="Remove a subscription")
    remove_parser.add_argument("repo_url", help="URL of the Gitee repository to remove")

    # 子命令：list
    list_parser = subparsers.add_parser("list", help="List all subscriptions")

    # 子命令：update
    update_parser = subparsers.add_parser("update", help="Update the report for a specific repository")
    update_parser.add_argument("repo_url", help="URL of the Gitee repository to update")

    # 子命令：exit
    subparsers.add_parser("exit", help="Exit the tool")

    # 子命令：help（argparse 自带支持）
    subparsers.add_parser("help", help="Show help message")

    # 修改子命令：daily
    daily_parser = subparsers.add_parser("daily", help="Generate daily progress report")
    daily_parser.add_argument("repo_url", help="URL of the Gitee repository for the daily report")

    # 修改子命令：summarize
    summarize_parser = subparsers.add_parser("summarize", help="Generate a summary report for a daily progress file")
    summarize_parser.add_argument("repo_url", help="URL of the Gitee repository for the summary report")

    return parser

def parse_repo_url(repo_url):
    """
    从 Gitee 仓库 URL 中提取 owner 和 repo 信息
    :param repo_url: 仓库的 URL，例如 https://gitee.com/owner/repo
    :return: (owner, repo)
    """
    try:
        parts = repo_url.rstrip("/").split("/")
        owner = parts[-2]
        repo = parts[-1]
        return owner, repo
    except (IndexError, ValueError):
        raise ValueError(f"Invalid repo URL: {repo_url}")

def main():
    """主程序"""
    # 创建命令行解析器
    parser = create_parser()

    # 解析命令行参数
    args = parser.parse_args()

    # 获取 Gitee Token，实际应用时可以从环境变量或配置文件读取
    token = "your_gitee_token"  # 请替换为您的 Gitee Token

    cli = GiteeSentinelCLI(token=token, scheduler_enabled=True)

    # 根据命令来执行相应的操作
    if args.command == "add" and args.repo_url:
        cli.handle_add_subscription(args.repo_url)
        print(f"Added subscription: {args.repo_url}")
    elif args.command == "remove" and args.repo_url:
        cli.handle_remove_subscription(args.repo_url)
        print(f"Removed subscription: {args.repo_url}")
    elif args.command == "list":
        cli.handle_list_subscriptions()
    elif args.command == "update" and args.repo_url:
        cli.handle_update_report(args.repo_url)
    elif args.command == "daily" and args.repo_url:
        cli.handle_daily(args.repo_url)
    elif args.command == "summarize" and args.repo_url:
        cli.handle_summarize(args.repo_url)
    elif args.command == "exit":
        cli.handle_exit()
    
    else:
        # 启动交互式模式
        cli.run()

if __name__ == "__main__":
    main()
